package com.water.waterojcodesandbox.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.water.waterojcodesandbox.constant.CodeSandBoxConstant;
import com.water.waterojcodesandbox.model.ExecuteCodeRequest;
import com.water.waterojcodesandbox.model.ExecuteCodeResponse;
import com.water.waterojcodesandbox.model.ExecuteMessage;
import com.water.waterojcodesandbox.model.JudgeInfo;
import com.water.waterojcodesandbox.model.enumeration.JudgeInfoMessageEnum;
import com.water.waterojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Java 代码沙箱模板方法的实现
 */
@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    // 设置超时时间为5秒
    private static final long TIME_OUT = 50000L;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        // 校验黑名单
        log.info("校验黑名单");
        try {
            checkBlackList(code);
        } catch (Exception e) {
            return getErrorResponse(e, JudgeInfoMessageEnum.DANGEROUS_OPERATION, null);
        }


        //  1. 把用户的代码保存为文件
        File userCodeFile = null;
        try {
            userCodeFile = saveCodeToFile(code);
        } catch (Exception e) {
            return getErrorResponse(e, JudgeInfoMessageEnum.FORMAT_ERROR, null);
        }


        log.info("将要开始编译");
        //  2. 编译代码，得到 class 文件
        ExecuteMessage compileFileExecuteMessage = null;
        try {
             compileFileExecuteMessage = compileFile(userCodeFile);
             log.info("编译信息: {}", compileFileExecuteMessage);
             if (compileFileExecuteMessage.getExitValue() != 0) {
                 throw new RuntimeException("编译错误");
             }
        } catch (Exception e) {
            return getErrorResponse(e, JudgeInfoMessageEnum.COMPILE_ERROR, userCodeFile);
        }


        // 3. 执行代码，得到输出结果
        List<ExecuteMessage> executeMessageList = null;
        try {
            executeMessageList = runFile(userCodeFile, inputList);
        } catch (Exception e) {
            return getErrorResponse(e, JudgeInfoMessageEnum.RUNTIME_ERROR, userCodeFile);
        }

        // 4. 收集整理输出结果
        ExecuteCodeResponse outputResponse = null;
        try {
            outputResponse = getOutputResponse(executeMessageList);
        } catch (Exception e) {
            return getErrorResponse(e, JudgeInfoMessageEnum.RUNTIME_ERROR, userCodeFile);
        }

        // 5. 文件清理
        boolean b = deleteFile(userCodeFile);
        if (!b) {
            log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsolutePath());
            try {
                throw new Exception("文件清理失败，内存无法释放");
            } catch (Exception e) {
                return getErrorResponse(e, JudgeInfoMessageEnum.SYSTEM_ERROR, null);
            }
        }
        return outputResponse;
    }

    /**
     * 校验黑名单
     */
    public void checkBlackList(String code) {
        WordTree wordTree = new WordTree();
        wordTree.addWords(CodeSandBoxConstant.blackList);
        FoundWord foundWord = wordTree.matchWord(code);
        if (foundWord != null && StrUtil.isNotBlank(foundWord.getFoundWord())) throw new RuntimeException("此程序存在敏感词");
    }

    /**
     * 1. 把用户的代码保存为文件
     * @param code 用户代码
     * @return
     */
    public File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        log.info("文件目录:" + globalCodePathName);
        // 1. 判断全局代码目录是否存在，没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        // 2. 把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        FileUtil.touch(userCodePath);
        log.info("需要编译的文件名: " + userCodePath);
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

    /**
     * 2、编译代码
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) throws Exception {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        Process compileProcess = Runtime.getRuntime().exec(compileCmd);
        ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
        return executeMessage;
    }

    /**
     * 3、执行文件，获得执行结果列表
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) throws Exception {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            Process runProcess = Runtime.getRuntime().exec(runCmd);
            long memory = Runtime.getRuntime().totalMemory();
            // 超时控制
            new Thread(() -> {
                try {
                    Thread.sleep(TIME_OUT);
                    runProcess.destroy();
                }  catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }).start();
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
            executeMessage.setMemory(memory - 98566000L);
            executeMessageList.add(executeMessage);
        }
        return executeMessageList;
    }

    /**
     * 4、获取输出结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) throws Exception {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        long maxMemory = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                throw new Exception("运行错误: " + errorMessage);
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            Long memory = executeMessage.getMemory();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
            if (memory != null) {
                maxMemory = Math.max(maxMemory, memory);
            }
        }
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(JudgeInfoMessageEnum.ACCEPTED.getValue());
        } else {
            throw new Exception("运行错误: 输入与输出数量不匹配");
        }
        executeCodeResponse.setOutputList(outputList);
        executeCodeResponse.setMessage("执行完毕!");
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        // 要借助第三方库来获取内存占用，非常麻烦，此处不做实现，这里设置一个默认的，这里只是为了跑通程序。最终咱用docker实现。
        judgeInfo.setMemory(maxMemory);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        log.info("成功执行: {}", executeCodeResponse);
        return executeCodeResponse;
    }

    /**
     * 5、删除文件
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
            boolean del = FileUtil.del(userCodeParentPath);
            log.info("{}", ("删除" + (del ? "成功" : "失败")));
            return del;
        }
        return true;
    }

    /**
     * 6、获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e, JudgeInfoMessageEnum judgeInfoMessageEnum, File userCodeFile) {
        // 清理文件
        if (userCodeFile != null) {
            boolean b = deleteFile(userCodeFile);
            if (!b) log.error("清理文件失败");
        }
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(judgeInfoMessageEnum.getValue());
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setMessage(judgeInfoMessageEnum.getText());
        executeCodeResponse.setJudgeInfo(judgeInfo);
        log.error("错误返回结果: {}", executeCodeResponse);
        return executeCodeResponse;
    }
}
